package com.zhuhjay.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zhuhjay.mapper.MemberMapper;
import com.zhuhjay.mapper.MembertypeMapper;
import com.zhuhjay.model.dto.MemberInsertDto;
import com.zhuhjay.model.dto.MemberRechargeDto;
import com.zhuhjay.model.dto.MemberUpdateDto;
import com.zhuhjay.model.entity.Member;
import com.zhuhjay.model.entity.Membertype;
import com.zhuhjay.model.entity.table.Tables;
import com.zhuhjay.model.vo.MemberVo;
import com.zhuhjay.service.MemberService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ZhuHJay
 * @date 2023/4/26 17:49
 */
@Service
public class MemberServiceImpl implements MemberService {

    @Resource
    private MemberMapper memberMapper;

    @Resource
    private MembertypeMapper membertypeMapper;

    @Override
    public List<MemberVo> list() {
        return memberMapper.selectAll().stream().map(member -> {
            MemberVo vo = new MemberVo();
            BeanUtil.copyProperties(member, vo);
            Membertype membertype = membertypeMapper.selectOneById(member.getTypeid());
            vo.setTypeName(membertype.getName());
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public void recharge(MemberRechargeDto dto) {
        Member member = memberMapper.selectOneByCondition(Tables.MEMBER.IDNUMBER.eq(dto.getIdNumber()));
        if (member == null) {
            throw new RuntimeException("会员不存在");
        }
        member.setBalance(member.getBalance() + dto.getAmount());
        memberMapper.update(member);
    }

    @Override
    public void insert(MemberInsertDto memberDto) {
        Member member = BeanUtil.copyProperties(memberDto, Member.class);
        member.setRegdate(new Date(System.currentTimeMillis()));
        memberMapper.insert(member);
    }

    @Override
    public void update(MemberUpdateDto memberVo) {
        Member member = memberMapper.selectOneById(memberVo.getId());
        if (member == null) {
            throw new RuntimeException("会员不存在");
        }
        BeanUtil.copyProperties(memberVo, member);
        memberMapper.update(member);
    }

    @Override
    public void delete(Integer id) {
        if (memberMapper.selectOneById(id) == null) {
            throw new RuntimeException("会员不存在");
        }
        memberMapper.deleteById(id);
    }

    @Override
    public MemberVo one(Integer id) {
        Member member = memberMapper.selectOneById(id);
        if (member == null) {
            throw new RuntimeException("会员不存在");
        }
        MemberVo vo = new MemberVo();
        BeanUtil.copyProperties(member, vo);
        Membertype membertype = membertypeMapper.selectOneById(member.getTypeid());
        vo.setTypeName(membertype.getName());
        vo.setAmount(membertype.getAmount());
        return vo;
    }

}
